{{ define "js" }}
  <script type="text/javascript" src="/js/datatables.min.js"></script>
  <script type="text/javascript" src="/js/datatable_input.js"></script>
  <script type="text/javascript" src="/js/datatable_loader.js"></script>
    <script>
        var validatorsDataTable;
        const totalCount = {{.TotalCount}};
        const depositedCount = {{.DepositedCount}};
        const pendingCount = {{.PendingCount}};
        const activeOnlineCount = {{.ActiveOnlineCount}};
        const activeOfflineCount = {{.ActiveOfflineCount}};
        const slashingOnlineCount = {{.SlashingOnlineCount}};
        const slashingOfflineCount = {{.SlashingOfflineCount}};
        const exitingOnlineCount = {{.ExitingOnlineCount}};
        const exitingOfflineCount = {{.ExitingOfflineCount}};
        const exitedCount = {{.ExitedCount}};
        const voluntaryExitsCount = {{.VoluntaryExitsCount}};
        const onlineCount = {{.ActiveOnlineCount}} + {{.SlashingOnlineCount}} + {{.ExitingOnlineCount}}
        const offlineCount = {{.ActiveOfflineCount}} + {{.SlashingOfflineCount}} + {{.ExitingOfflineCount}}

        var stateFilterDropDownHtml = `<div><label>
            <div class="dropdown" style="display:inline-block;">
            <button class="btn btn-primary dropdown-toggle text-white" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"><span>All ${totalCount}</span></button>
            <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
            <h6 class="dropdown-header"><span>Filter state</span> <span><span class="text-success">online</span> | <span class="text-danger">offline</span></span></h6>
            <hr style="margin:0.5rem 0">
            <a class="dropdown-item" href="#all" data-filter-validators="all"><span>All</span> <span>${totalCount}</span></a>
            <a class="dropdown-item" href="#online" data-filter-validators="online"><span>Online</span> <span>${onlineCount}</span></a>
            <a class="dropdown-item" href="#offline" data-filter-validators="offline"><span>Offline</span> <span>${offlineCount}</span></a>
            <a class="dropdown-item" href="#active" data-filter-validators="active"><span>Active</span><span> <span class="text-success">${activeOnlineCount}</span> | <span class="text-danger">${activeOfflineCount}</span></span></a>
            <a class="dropdown-item" href="#slashing" data-filter-validators="slashing"><span>Slashing</span><span> <span class="text-success">${slashingOnlineCount}</span> | <span class="text-danger">${slashingOfflineCount}</span></span></a>
            <a class="dropdown-item" href="#deposited" data-filter-validators="deposited"><span>Deposited</span> <span>${depositedCount}</span></a>
            <a class="dropdown-item" href="#pending" data-filter-validators="pending"><span>Pending</span> <span>${pendingCount}</span></a>
            <a class="dropdown-item" href="#exiting" data-filter-validators="exiting"><span>Exiting</span><span> <span class="text-success">${exitingOnlineCount}</span> | <span class="text-danger">${exitingOfflineCount}</span></span></a>
            <a class="dropdown-item" href="#exited" data-filter-validators="exited"><span>Exited</span> <span>${exitedCount}</span></a>
            <a class="dropdown-item" href="#voluntary" data-filter-validators="voluntary"><span>Vol. Exits</span> <span>${voluntaryExitsCount}</span></a>
            </div>
        </div>
    </label></div>`;

        function adaptTableToState(state) {
            $('.filter-by-status a.dropdown-item').removeClass('active');
            $(`.filter-by-status a[data-filter-validators=${state}]`).addClass('active');
            $('.filter-by-status .btn:first-child').html($(`.filter-by-status a[data-filter-validators=${state}]`).html());
            // 0pubkey, 1idx, 2bal, 3state, 4active, 5exit, 6withdraw, 7lastattest, 8slashed
            if (state === "all" || state === "offline" || state === "online") {
                validatorsDataTable.column(3).visible(true);
                validatorsDataTable.column(4).visible(true);
                validatorsDataTable.column(5).visible(true);
                validatorsDataTable.column(6).visible(true);
                validatorsDataTable.column(7).visible(true);
                validatorsDataTable.column(8).visible(false);
            } else if (state === "pending") {
                validatorsDataTable.column(3).visible(true);
                validatorsDataTable.column(4).visible(true);
                validatorsDataTable.column(5).visible(false);
                validatorsDataTable.column(6).visible(false);
                validatorsDataTable.column(7).visible(false);
                validatorsDataTable.column(8).visible(false);
            } else if (state === "active" || state === "slashing" || state === "exiting") {
                validatorsDataTable.column(3).visible(true);
                validatorsDataTable.column(4).visible(true);
                validatorsDataTable.column(5).visible(false);
                validatorsDataTable.column(6).visible(false);
                validatorsDataTable.column(7).visible(true);
                validatorsDataTable.column(8).visible(false);
            } else if (state === "exited") {
                validatorsDataTable.column(3).visible(false);
                validatorsDataTable.column(4).visible(true);
                validatorsDataTable.column(5).visible(true);
                validatorsDataTable.column(6).visible(true);
                validatorsDataTable.column(7).visible(false);
                validatorsDataTable.column(8).visible(true);
            } else if (state === "voluntary") {
                validatorsDataTable.column(3).visible(false);
                validatorsDataTable.column(4).visible(true);
                validatorsDataTable.column(5).visible(true);
                validatorsDataTable.column(6).visible(true);
                validatorsDataTable.column(7).visible(false);
                validatorsDataTable.column(8).visible(false);
            } else if (state === "deposited") {
                validatorsDataTable.column(3).visible(true);
                validatorsDataTable.column(4).visible(false);
                validatorsDataTable.column(5).visible(false);
                validatorsDataTable.column(6).visible(false);
                validatorsDataTable.column(7).visible(false);
                validatorsDataTable.column(8).visible(false);
            }
        }

        $(document).ready(function() {
            var state = 'all';
            var possibleStates = {
                all: true,
                pending: true,
                active: true,
                slashing: true,
                exiting: true,
                exited: true,
                voluntary: true,
                deposited: true
            };
            if (window.location.hash) {
                var hashState = window.location.hash.substring(1);
                if (possibleStates[hashState]) state = hashState
            }
            var urlSearchParams = new URLSearchParams([["filterByState", state]])

            var usp = new URLSearchParams(window.location.search)
            var q = usp.get('q')

            validatorsDataTable = $('#validators').DataTable({
                search: q ? {search:q} : null,
                pageLength: 25,
                searchDelay: 0,
                processing: true,
                serverSide: true,
                searching: false,
                stateSave: true,
                stateSaveCallback: function (settings, data) {
                  data.start = 0
                  localStorage.setItem("DataTables_" + settings.sInstance, JSON.stringify(data))
                },
                stateLoadCallback: function (settings) {
                  return JSON.parse(localStorage.getItem("DataTables_" + settings.sInstance))
                },
                ajax: dataTableLoader('/validators/data', urlSearchParams),
                pagingType: 'input',
                language: {
                    paginate: {
                        previous: '<i class="fas fa-chevron-left"></i>',
                        next: '<i class="fas fa-chevron-right"></i>'
                    },
                    search: '',
                    searchPlaceholder: 'Search...'
                },
                dom: "<'row'<'col-sm-12 col-md-6 filter-by-status'><'col-sm-12 col-md-6'f>>" +
                    "<'row'<'col-sm-12'tr>>" +
                    "<'row'<'col-sm-12 col-md-5'l><'col-sm-12 col-md-7'p>>",
                fnInitComplete: function() {
                    $('.filter-by-status')
                        .html(stateFilterDropDownHtml)
                        .find('[data-filter-validators]')
                        .click(function() {
                            var f = $(this).data('filter-validators');
                            urlSearchParams.set("filterByState", f)
                            validatorsDataTable.ajax.reload();
                            adaptTableToState(f)
                        });
                    adaptTableToState(state)
                },
                preDrawCallback: function() {
                    // this does not always work.. not sure how to solve the staying tooltip
                    try {
                        $('#validators').find('[data-toggle="tooltip"]').tooltip('dispose')
                    } catch (e) {
                        console.error(e)
                    }
                },
                drawCallback: function() {
                    formatTimestamps()
                    $('#validators').find('[data-toggle="tooltip"]').tooltip();
                    validatorsDataTable.columns.adjust().responsive.recalc()
                },
                columnDefs: [
                    {
                        targets: 0,
                        data: '0',
                        createdCell: function(td, cellData, rowData, row, col) {
                            $(td).css('display', 'flex');
                            $(td).css('align-items', 'center');
                            $(td).css('justify-content', 'space-between');
                        },
                        render: function(data, type, row, meta) {
                            // return '<a href="/validator/' + data + '">0x' + data.substr(0, 8) + '...</a>'
                            return `<a href="/validator/${data}">0x${data.substr(0, 8)}...</a><i class="fa fa-copy text-muted p-1" role="button" data-toggle="tooltip" title="Copy to clipboard" data-clipboard-text="0x${data}"></i>`
                        }
                    },
                    {
                        targets: 1,
                        data: '1',
                        render: function(data, type, row, meta) {
                            var title = data
                            if (row[9]) { // If a name for a validator is present display it alongside the index
                                title = data + ' (<span class="text-truncate">' + row[9] + '</span>)'
                            }
                            return '<a href="/validator/' + data + '">' + title + '</a>'
                        }
                    },
                    {
                        targets: 2,
                        data: '2',
                        orderable: false,
                        render: function(data, type, row, meta) {
                            return `${data[0]} (${data[1]})`
                        }
                    },
                    {
                        targets: 3,
                        data: '3',
                        render: function(data, type, row, meta) {
                            var d = data.split('_');
                            var s = d[0].charAt(0).toUpperCase() + d[0].slice(1);
                            if (d[1] === 'offline')
                                return `<span data-toggle="tooltip" data-placement="top" title="No attestation in the last 2 epochs">${s} <i class="fas fa-power-off fa-sm text-danger"></i></span>`;
                            if (d[1] === 'online')
                                return `<span>${s} <i class="fas fa-power-off fa-sm text-success"></i></span>`;
                            return `<span>${s}</span>`
                        }
                    },
                    {
                        targets: 4,
                        data: '4',
                        render: function(data, type, row, meta) {
                            // 9223372036854775808 gets rounded up as it is above the Number.MAX_SAFE_INTEGER value
                            if (data === null || data[0] === 9223372036854776000)
                                return '-';
                            return `<span><span class="timestamp" data-toggle="tooltip" data-placement="top" data-timestamp="${data[1]}"></span> (<a href="/epoch/${data[0]}">Epoch ${addCommas(data[0])}</a>)</span>`
                        }
                    },
                    {
                        targets: 5,
                        data: '5',
                        render: function(data, type, row, meta) {
                            if (data === null)
                                return '-';
                            return `<span><span class="timestamp" data-toggle="tooltip" data-placement="top" data-timestamp="${data[1]}"></span> (<a href="/epoch/${data[0]}">Epoch ${addCommas(data[0])}</a>)</span>`
                        }
                    },
                    {
                        targets: 6,
                        data: '6',
                        render: function(data, type, row, meta) {
                            if (data === null)
                                return '-';
                            return `<span><span class="timestamp" data-toggle="tooltip" data-placement="top" data-timestamp="${data[1]}"></span> (<a href="/epoch/${data[0]}">Epoch ${addCommas(data[0])}</a>)</span>`
                        }
                    },
                    {
                        targets: 7,
                        data: '7',
                        orderable: false,
                        render: function(data, type, row, meta) {
                            if (data === null)
                                return 'No Attestation found';
                            return `<span><span class="timestamp" data-toggle="tooltip" data-placement="top" data-timestamp="${data[1]}"></span> (<a href="/slot/${data[0]}">Block ${addCommas(data[0])}</a>)</span>`
                        }
                    },
                    {
                        targets: 8,
                        data: '8',
                        render: function(data, type, row, meta) {
                            if (data === true) {
                               return `<span data-toggle="tooltip" data-placement="top" title="slashed" class="text-danger">true</span>`
                            }
                            return `<span data-toggle="tooltip" data-placement="top" title="unslashed" class="text-success">false</span>`
                        }
                    },
                ]
            })
            $("#validators_filter > label > input").on('input', function(ev) {
                if (ev && ev.target && ev.target.value) {
                    var newUrl = window.location.pathname + "?q=" + encodeURIComponent(ev.target.value)
                    window.history.replaceState(null, 'Validators Overview', newUrl)
                } else {
                    window.history.replaceState(null, 'Validators Overview', window.location.pathname)
                }
            })
        })
    </script>
{{ end }}
{{ define "css" }}
  <link rel="stylesheet" type="text/css" href="/css//datatables.min.css" />
  <style>
    .dataTables_wrapper {
      min-height: 400px; /* this is needed to make the bootstrap-dropdown work when the table is empty */
    }

    .filter-by-status {
      padding-left: 1rem !important;
    }

    #validators_wrapper .dropdown-item:focus,
    #validators_wrapper .dropdown-item:hover {
      color: var(--font-color);
      background-color: var(--bg-color-nav);
    }

    #validators_wrapper .dropdown-menu {
      color: var(--font-color);
      background-color: var(--bg-color-secondary);
    }

    #validators_wrapper .dropdown-header {
      padding: 0.25rem 1rem;
      color: var(--body-color);
      display: flex;
    }

    #validators_wrapper .dropdown-header > span:nth-child(1) {
      width: 40%;
    }

    #validators_wrapper .dropdown-header > span:nth-child(2) {
      width: 60%;
      padding-left: 0.5rem;
    }

    #validators_wrapper .dropdown-item {
      display: flex;
      padding: 0.25rem 1rem;
      color: var(--font-color);
    }

    #validators_wrapper .dropdown-item > span:nth-child(1) {
      width: 40%;
      min-width: 80px;
    }

    #validators_wrapper .dropdown-item > span:nth-child(2) {
      width: 60%;
      min-width: 130px;
      padding-left: 0.5rem;
    }
  </style>
{{ end }}
{{ define "content" }}
  {{ with .Data }}
    <div class="container mt-2">
      <div class="my-3">
        <div class="d-md-flex py-2 justify-content-md-between">
          <h1 class="h4 mb-1 mb-md-0"><i class="fas fa-user-shield"></i> Validators Overview</h1>
          <nav aria-label="breadcrumb">
            <ol class="breadcrumb font-size-1 mb-0" style="padding:0; background-color:transparent;">
              <li class="breadcrumb-item"><a href="/" title="Home">Home</a></li>
              <li class="breadcrumb-item"><a href="/validators" title="Validators">Validators</a></li>
              <li class="breadcrumb-item active" aria-current="page">Overview</li>
            </ol>
          </nav>
        </div>
      </div>
      <h6 class="my-2">This table only shows the first 10000 validators of the resultset for the given sorting and filters.</h6>
      <div class="card">
        <div class="card-body px-0 py-2">
          <div class="table-responsive pt-2">
            <table class="table" id="validators">
              <thead>
                <tr>
                  <th>Public Key</th>
                  <th>Index</th>
                  <th>Balance</th>
                  <th>State</th>
                  <th>Activation</th>
                  <th>Exit</th>
                  {{ with .CappellaHasHappened }}
                    <th title="Withdrawable epoch number&#013;">W/able</th>
                  {{ else }}
                    <th title="Withdrawable epoch number&#013;Please note that the withdraw functionality has not been implemented by ACD yet.">W/able</th>
                  {{ end }}
                  <th>Last Attestation</th>
                  <th>Slashed</th>
                </tr>
              </thead>
              <tbody></tbody>
            </table>
          </div>
        </div>
      </div>
      <div id="r-banner" info="{{ $.Meta.Templates }}"></div>
    </div>
  {{ end }}
{{ end }}
